<?php
/**
 * @ClassName: Incomerecords
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-16 19:05
 * @Version: V1.0.0
 */

namespace app\api\controller\water;

use app\api\controller\Api;
use app\common\model;

class Incomerecords extends Api
{
    protected $platform_ratio = 5;//平台收益比例
    protected $center_ratio = 5;//运营中心收益比例
    protected $direct_ratio = 10;//直推收益比例

    public function initialize()
    {
        $config = web_config('task_income');
        if ($config) {
            $this->platform_ratio = $config['platform_ratio_t'];
            $this->center_ratio = $config['center_ratio_t'];
            $this->direct_ratio = $config['direct_ratio_t'];
        }
    }

    /**
     * 我的收益
     * @return \think\response\Json
     */
    function getMyIncome()
    {
        $type = input('type', 'task_income');

        $amount = 0;
        try {
            if ($type) {
                $amount = model\Member::where('id', $this->user_id)->value($type);
            }
//            return json(['code' => 1, 'data' => round($amount, 2)]);//四舍五入后保留小数位
//            return json(['code' => 1, 'data' => number_format($amount, 2)]);//四舍五入后保留小数位并格式化输出
            return json(['code' => 1, 'data' => sprintf("%.4f", $amount)]);//不做四舍五入，并保留小数位
        } catch (\Exception $e) {

        }
        return json(['code' => 0, 'data' => number_format($amount, 2)]);
    }

    /**
     * 收益记录
     * @return \think\response\Json
     */
    function list()
    {
        $type = input('type');//收益类型：0推广收益，1代理收益，2广告收益，3任务收益
        $current = input('current', 0);
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];
        $where[] = ['member_id', 'eq', $this->user_id];
        $where[] = ['type', 'eq', $type];
        switch ($current) {
            case 1:
                //收入
                $where[] = ['trade_fee_type', 'eq', 1];
                break;
            case 2:
                //支出
                $where[] = ['trade_fee_type', 'eq', 0];
                break;
            default:
                //全部
                break;
        }

        $list = model\IncomeRecords::where($where)->order('create_time desc')->limit($skip, $limit)->select();

        $result = [
            'data' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 领取任务奖励
     * @return \think\response\Json
     */
    function taskRewards()
    {
        $areaCode = input('areaCode');
        $token = input('token');
        $date = date('Y-m-d');

        $member = model\Member::where(array('token' => $token))->find();
        if (!$member) {
            return json(["code" => 0, "msg" => "用户未登录，请先登录"]);
        }

        $member_id = $member['id'];
        $operation_income = 0;
        $direct_income = 0;

        //当日领取次数
        $count = model\IncomeRecords::where('member_id', $member_id)->where('create_time', 'like', '%' . $date . '%')->count();
        switch ($count) {
            case 0:
                $amount = 0.1;
                break;
            case 1:
                $amount = 0.05;
                break;
            case 2:
                $amount = 0.03;
                break;
            default:
                $amount = 0.01;
                break;
        }

        makelog('领取广告任务奖励', 'api/income/taskRewards');
        makelog('观看广告用户：' . $member_id, 'api/income/taskRewards');
        makelog('今日观看广告领取奖励次数：' . $count, 'api/income/taskRewards');
        makelog('本次观看广告可领取奖励：' . $amount, 'api/income/taskRewards');

        // 平台收益5%
        $platform_income = round($amount * $this->platform_ratio / 100, 4);
        makelog('平台收益（' . $this->platform_ratio . '%）：' . $platform_income, 'api/income/taskRewards');
        if ($platform_income > 0) {
            $this->addIncome(env('ad_income_uid'), $platform_income, '平台收益', 'platformIncome');
        }

        // 运营中心收益5%（530102003000）
        if (strlen($areaCode) >= 9) {
            /*// 获取区县运营中心
            $area = substr($areaCode, 0, 6);
            $operation_area = model\agent\OperationCenter::where('center_type', 1)->where('area', $area)->find();

            $operation_member_id = 0;
            $note = '';
            $tag = '';

            if ($operation_area) {
                $operation_income = round($amount * $this->center_ratio / 100, 4);
                makelog('区县运营中心收益（' . $this->center_ratio . '%）：' . $operation_income, 'api/income/taskRewards');
                $operation_member_id = $operation_area['member_id'];
                $note = '区县运营中心收益';
                $tag = 'operationAreaIncome';
            } else {
                // 获取市级运营中心
                $city = substr($areaCode, 0, 4);
                $operation_city = model\agent\OperationCenter::where('center_type', 2)->where('city', $city)->find();

                if ($operation_city) {
                    $operation_income = round($amount * $this->center_ratio / 100, 4);
                    makelog('市级运营中心收益（' . $this->center_ratio . '%）：' . $operation_income, 'api/income/taskRewards');
                    $operation_member_id = $operation_city['member_id'];
                    $note = '市级运营中心收益';
                    $tag = 'operationCityIncome';
                } else {
                    // 获取省级运营中心
                    $province = substr($areaCode, 0, 2);
                    $operation_province = model\agent\OperationCenter::where('center_type', 3)->where('province', $province)->find();

                    if ($operation_province) {
                        $operation_income = round($amount * $this->center_ratio / 100, 4);
                        makelog('省级运营中心收益（' . $this->center_ratio . '%）：' . $operation_income, 'api/income/taskRewards');
                        $operation_member_id = $operation_province['member_id'];
                        $note = '省级运营中心收益';
                        $tag = 'operationProvinceIncome';
                    }
                }
            }

            if ($operation_income > 0) {
                $this->addIncome($operation_member_id, $operation_income, $note, $tag);
            }*/

            // 获取市级运营中心
            $city = substr($areaCode, 0, 4);
            $operation_city = model\agent\OperationCenter::where('center_type', 2)->where('city', $city)->find();

            if ($operation_city) {
                $operation_income = round($amount * $this->center_ratio / 100, 4);
                makelog('市级运营中心收益（' . $this->center_ratio . '%）：' . $operation_income, 'api/income/taskRewards');
                $operation_member_id = $operation_city['member_id'];
                $note = '市级运营中心收益';
                $tag = 'operationCityIncome';

                if ($operation_income > 0) {
                    $this->addIncome($operation_member_id, $operation_income, $note, $tag);
                }
            } else {
                // 没有市级运营中心，运营中心收益分给平台
                $operation_income = round($amount * $this->center_ratio / 100, 4);
                if ($operation_income > 0) {
                    $this->addIncome(env('ad_income_uid'), $operation_income, '平台收益 - 运营中心', 'platformIncome');
                }
            }
        } else {
            // 没有定位，运营中心收益分给平台
            $operation_income = round($amount * $this->center_ratio / 100, 4);
            if ($operation_income > 0) {
                $this->addIncome(env('ad_income_uid'), $operation_income, '平台收益 - 运营中心', 'platformIncome');
            }
        }

        // 直推收益10%
        $superior = model\Member::where('id', $member['first_leader'])->find();
        if ($superior) {
            $direct_income = round($amount * $this->direct_ratio / 100, 4);
            makelog('直推收益（' . $this->direct_ratio . '%）：' . $direct_income, 'api/income/taskRewards');
            $this->addIncome($superior['id'], $direct_income, '直推收益', 'directIncome');
        }

        // 用户收益 = 观看广告收益 - 平台收益 - 运营中心收益 - 直推收益;
        $user_income = round($amount - $platform_income - $operation_income - $direct_income, 4);
        makelog('用户收益：' . $user_income, 'api/income/taskRewards');
        if ($user_income > 0) {
            $this->addIncome($member_id, $user_income, '用户收益', 'userIncome');
        }

        return json(["code" => 1, "msg" => "任务奖励领取成功"]);
    }

    /**
     * 添加收益记录
     * @param $member_id
     * @param $amount
     * @param $note
     * @param $tag
     * @return void
     */
    private function addIncome($member_id, $amount, $note, $tag)
    {
        $member = model\Member::where('id', $member_id)->find();
        model\IncomeRecords::insert([
            'type' => 3,//收益类型：0推广收益，1代理收益，2广告收益，3任务收益
            'name' => '任务收益',
            'trade_no' => '',
            'trade_type' => 0,
            'amount' => $amount,
            'status' => 0,
            'trade_fee_type' => 1,
            'note' => $note,
            'tag' => $tag,
            'member_id' => $member_id
        ]);
        //更新用户信息
        $task_income = bcadd($member['task_income'], $amount, 4);
        model\Member::where('id', $member_id)->update(['task_income' => $task_income]);
    }

}